package com.yjd.comm.user.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.util.TxtFileCacheUtil;

/**
 * <b>description</b>：登陆url返回 <br>
 * <b>time</b>：2015-1-19下午8:55:44 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class LoginReturnUrlUtil {
	private static String NORETURNURL_FILE = "noreturnurl.txt";

	/**
	 * 获取登陆以后跳转的页面
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String getReturnUrl(HttpServletRequest request) throws Exception {
		String returnUrl = request.getParameter(ServletUtil.returnUrl);
		if (StringUtil.isEmpty(returnUrl)) {
			returnUrl = ServletUtil.getReferer(request);
		}
		if (StringUtil.isNotEmpty(returnUrl)) {
			try {
				String host = ServletUtil.domainHost();
				URL url = new URL(returnUrl);
				String returnUrlHost = url.getHost();
				if (returnUrlHost.indexOf(host) == 0 || getNotReturnUrl().contains(returnUrl)) {
					returnUrl = null;
				}
			} catch (Exception e) {
				returnUrl = null;
			}
		}
		return returnUrl;
	}

	private static List<String> getNotReturnUrl() {
		List<String> noReturnUrl = new ArrayList<String>();
		List<String> list = TxtFileCacheUtil.get(NORETURNURL_FILE);
		for (String s : list) {
			noReturnUrl.add(ServletUtil.getUrl(s));
		}
		return noReturnUrl;
	}

	public static void main(String[] args) throws MalformedURLException {
		System.out.println(System.currentTimeMillis());
		URL url = new URL("http://admin.itsoku.com/");
		System.out.println(System.currentTimeMillis());
		System.out.println(url);
	}
}
